/**
 * @author Shine
 */

package com.shine.utils
{
	import flash.display.DisplayObject;
	import flash.system.ApplicationDomain;
	import flash.utils.getDefinitionByName;
	import flash.utils.getQualifiedClassName;

	public class ClassUtil
	{

		public static function createDisplayObjectInstance(fullClassName:String, applicationDomain:ApplicationDomain=null):DisplayObject
		{
			return createInstance(fullClassName, applicationDomain)as DisplayObject;
		}

		public static function createInstance(fullClassName:String, applicationDomain:ApplicationDomain=null):*
		{
			var assetClass:Class=getClass(fullClassName, applicationDomain);
			if (assetClass != null)
			{
				return new assetClass();
			}
			return null;
		}

		public static function getClass(fullClassName:String,applicationDomain:ApplicationDomain=null):Class
		{
			if(applicationDomain==null) return Class(getDefinitionByName(fullClassName));
			return applicationDomain.getDefinition(fullClassName) as Class;
		}

		public static function getFullClassName(o:*):String
		{
			return getQualifiedClassName(o);
		}

		public static function getClassName(o:*):String
		{
			var name:String=getFullClassName(o).replace("::", ".");
			var lastI:int=name.lastIndexOf(".");
			if (lastI >= 0)
			{
				name=name.substr(lastI + 1);
			}
			return name;
		}

		public static function getPackageName(o:*):String
		{
			var name:String=getFullClassName(o);
			var lastI:int=name.lastIndexOf(".");
			if (lastI >= 0)
			{
				return name.substring(0, lastI);
			}
			else
			{
				return "";
			}
		}
		
		public static function classOf(o:Object):Class
		{
			return (((o is Class)) ? Class(o) : Class(getDefinitionByName(getQualifiedClassName(o))));
		}
		
		public static function toString(c:*,...rest):String 
		{
			var output:String;
			var n:int;
			var prop:String;
			var object:* = c;
			var properties:Array = rest;
			output ="[";
			output+= getClassName(object);
			var i:int;
			n = properties.length;
			var m:int = (n - 1);
			while (i < n) {
				prop = properties[i];
				output = (output + ((" " + prop) + ": "));
				try {
					output = (output + object[prop]);
				} catch(error:Error) {
					output = (output + (("(" + error.message) + ")"));
				};
				if (i != m){
					output = (output + ",");
				};
				i = (i + 1);
			};
			output = (output + "]");
			return output;
		}
	}
}